﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Net;

using FinancialAnalytic.BusinessLogic;


namespace FinancialAnalytic.BusinessLogic
{
    public class StockQuoteDownloader : AbstractDataDownloader
    {
        #region private fields
        private string m_historydata = string.Empty;
        private string m_symbol = string.Empty;
        private DateTime? m_startDate = new DateTime();
        private DateTime? m_endDate = new DateTime();
        private DataTable m_dt = new DataTable();
        
        // For Downloading Data with Start Date and End Date
        private string urlTemplate =
           @"http://ichart.finance.yahoo.com/table.csv?s=[symbol]&a=" +
             "[startMonth]&b=[startDay]&c=[startYear]&d=[endMonth]&e=" +
                "[endDay]&f=[endYear]&g=d&ignore=.csv";  
        #endregion


        public DataTable YahooData(string symbol, DateTime? startDate, DateTime? endDate)
        {
            this.m_symbol = symbol;
            this.m_startDate = startDate;
            this.m_endDate = endDate;
            SetProperties(m_symbol,m_startDate,m_endDate);
            this.m_dt = CreateDataTable(m_symbol, m_startDate, m_endDate);

            return m_dt;
        }
 
        private DataTable CreateDataTable(string symbol, DateTime? startDate, DateTime? endDate)
        {
           
            string history = String.Empty;
            history = HistoryData(urlTemplate);

            DataTable dt = new DataTable();
            // trim off unused characters from end of line
            history = history.Replace("\r", "");
            // split to array on end of line
            string[] rows = history.Split('\n');
            // split to colums
            string[] colNames = rows[0].Split(',');
            // add the columns to the DataTable
            foreach (string colName in colNames)
                dt.Columns.Add(colName);
            DataRow row = null;
            string[] rowValues;
            object[] rowItems;
            // split the rows
            for (int i = rows.Length - 1; i > 0; i--)
            {
                rowValues = rows[i].Split(',');
                row = dt.NewRow();
                rowItems = ConvertStringArrayToObjectArray(rowValues);
                if (rowItems[0] != null && (string)rowItems[0] != "")
                {
                    row.ItemArray = rowItems;
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        private void SetProperties(string symbol, DateTime? startDate, DateTime? endDate)
        {
            if (!endDate.HasValue) endDate = DateTime.Now;
            if (!startDate.HasValue) startDate = DateTime.Now.AddYears(-5);
            if (symbol == null || symbol.Length < 1)
                throw new ArgumentException("Symbol invalid: " + symbol);
            // NOTE: Yahoo's scheme uses a month number 1 less than actual e.g. Jan. ="0"
            int strtMo = startDate.Value.Month - 1;
            string startMonth = strtMo.ToString();
            string startDay = startDate.Value.Day.ToString();
            string startYear = startDate.Value.Year.ToString();

            int endMo = endDate.Value.Month - 1;
            string endMonth = endMo.ToString();
            string endDay = endDate.Value.Day.ToString();
            string endYear = endDate.Value.Year.ToString();

            urlTemplate = urlTemplate.Replace("[symbol]", symbol);

            urlTemplate = urlTemplate.Replace("[startMonth]", startMonth);
            urlTemplate = urlTemplate.Replace("[startDay]", startDay);
            urlTemplate = urlTemplate.Replace("[startYear]", startYear);

            urlTemplate = urlTemplate.Replace("[endMonth]", endMonth);
            urlTemplate = urlTemplate.Replace("[endDay]", endDay);
            urlTemplate = urlTemplate.Replace("[endYear]", endYear);

            //return urlTemplate;


        }

        private object[] ConvertStringArrayToObjectArray(string[] input)
        {
            int elements = input.Length;
            object[] objArray = new object[elements];
            input.CopyTo(objArray, 0);
            return objArray;
        }
    }
}
